<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" %>
	<% String path=request.getContextPath(); String basePath=request.getScheme() + "://" + request.getServerName() + ":"
		+ request.getServerPort() + path + "/" ; %>

		<!DOCTYPE html>
		<html>

		<head>
			<base href="<%=basePath%>">

			<title>采购发票</title>

			<meta http-equiv="pragma" content="no-cache">
			<meta http-equiv="cache-control" content="no-cache">
			<meta http-equiv="expires" content="0">
			<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
			<meta http-equiv="description" content="This is my page">
			<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

		</head>

		<body>
			<%@ include file="/WEB-INF/jsp/common/header.jsp" %>
				<%@ include file="/WEB-INF/jsp/common/loadDiv.jsp" %>

					<script type="text/javascript">
						$(function () {
							$('#startTime').datebox('setValue', getBeforeCurrentDate90Days());
							$('#endTime').datebox('setValue', getNowFormatDate());
							$('#startGoodTime').datebox('setValue', getBeforeCurrentDate90Days());
							$('#endGoodTime').datebox('setValue', getNowFormatDate());
							bindgrid();
							bindBillsGrid({ groId: '-1' });
							bindGoodsList({ groId: '-1' });
							bindChoiseGoodsList();
							if (PUser.superadmin != '1') {
								$('#btnBack').hide();
							}
						})
					</script>
					<script>
						function del(node) {
							$.ajax({
								type: "delete",
								url: 'purchase/bill/group/delete?id=' + node.groId,
								//                dataType: "xml",				
								success: function (data) {
									$.messager.alert('消息', data.msg);
									let dg = $('#dg');
									dg.datagrid('enableFilter');
									dg.datagrid('load');
								},
								error: function (XMLHttpRequest, textStatus, errorThrown) {
									$.messager.alert('消息', errorThrown);
								}
							});
						}
						//计算价税合计
						function calBillsTotalPrice(rows) {
							for (var i in rows) {
								rows[i].bilTotalPrice = (Number(rows[i].bilPrice) + Number(rows[i].bilTaxPrice)).toFixed(4);
							}
							return rows
						}
						//累计价税合计
						function sumgroTotalPrice(rows) {
							var result = 0;
							for (var i in rows) {
								result = Number(result) + Number(rows[i].bilTotalPrice);
							}
							return result.toFixed(4);
						}
						//累计税额
						function sumgroTaxPrice(rows) {
							var result = 0;
							for (var i in rows) {
								result = Number(result) + Number(rows[i].bilTaxPrice);
							}
							return result.toFixed(4);
						}
						//累计发票金额
						function sumPrice(rows) {
							var result = 0;
							for (var i in rows) {
								result = Number(result) + Number(rows[i].bilPrice);
							}
							return result.toFixed(4);
						}
						//累计发票数量
						function sumNum(rows) {
							var result = 0;
							for (var i in rows) {
								result = Number(result) + Number(rows[i].bilNum);
							}
							return result.toFixed(4);
						}
						//计算累计原发数量
						function sumOldNum(rows) {
							var result = 0;
							for (var i in rows) {
								result = Number(result) + Number(rows[i].godOldNum);
							}
							return result.toFixed(4);
						}
						//计算累计实收数量
						function sumReceiveNum(rows) {
							var result = 0;
							for (var i in rows) {
								result = Number(result) + Number(rows[i].godNewNum);
							}
							return result.toFixed(4);
						}
						//累计开票数量
						function sumOpenNum(rows) {
							var result = 0;
							for (var i in rows) {
								result = Number(result) + Number(rows[i].godBillNum);
							}
							return result.toFixed(4);
						}
						//累计开票金额
						function sumOpenPrice(rows) {
							var result = 0;
							for (var i in rows) {
								result = Number(result) + Number(rows[i].godMoney);
							}
							return result.toFixed(4);
						}
						//保存
						function save(action) {
							if (!$('#fm').form('validate')) {
								alert('请先完成数据录入!');
								return;
							} if (!endEditing()) {
								return;
							}

							$('#billsList').datagrid('acceptChanges');
							var billModels = calBillsTotalPrice($('#billsList').datagrid('getRows'));
							var billGoodModels = $('#goodsList').datagrid('getRows');
							console.log('billModels:', $('#billsList').datagrid('getRows'));
							console.log('billGoodModels:', $('#goodsList').datagrid('getRows'));
							var model = {
								groId: $('#groId').val(),
								groName: $('#groName').textbox('getValue'),
								groCode: $('#groCode').textbox('getValue'),
								groOldNum: sumOldNum($('#goodsList').datagrid('getRows')),
								groReceiveNum: sumReceiveNum($('#goodsList').datagrid('getRows')),
								groOpenNum: sumOpenNum($('#goodsList').datagrid('getRows')),
								groPrice: sumPrice($('#billsList').datagrid('getRows')),
								groNum: sumNum($('#billsList').datagrid('getRows')),
								groTaxPrice: sumgroTaxPrice($('#billsList').datagrid('getRows')),
								groTotalPrice: sumgroTotalPrice($('#billsList').datagrid('getRows')),
								groOpenPrice: sumOpenPrice($('#goodsList').datagrid('getRows')),
								// infCode: $('#infCode').textbox('getValue'),
								// infName: $('#infName').textbox('getValue'),
								status: action == 'save' ? '0' : '1',
								sapStatus: action == 'save' ? '0' : '1',
								remark: $('#remark').textbox('getValue'),
								oaCheckId: $('#oaCheckCob').combobox('getValue'),
								oaCheckName: $('#oaCheckCob').combobox('getText'),
								billModels: billModels,
								billGoodModels: billGoodModels
							};
							console.log(model)
							if ((Number(model.groOpenNum) - Number(model.groNum)) != 0) {
								$.messager.alert('消息', '发票累计数量' + model.groNum + '与待开票累计数量' + model.groOpenNum + '不一致！');
								return;
							}
							if ((Number(model.groPrice) - Number(model.groOpenPrice)) != 0) {
								$.messager.confirm('提示', '发票累计金额' + model.groPrice + '和待开票累计金额' + model.groOpenPrice + '不一致，确定下一步?', function (r) {
									if (r) {
										$.ajax({
											type: "post",
											dataType: "json",
											url: 'purchase/bill/group/check',
											data: JSON.stringify(model),
											contentType: "application/json",
											success: function (data) {
												$.messager.alert('消息', data.msg);
												if (data.code != 60200) {
												} else {
													$('#groId').val(data.data.groId)
													let dg = $('#dg');
													dg.datagrid('enableFilter');
													dg.datagrid('load');
													$('#addWindow').window('close');
												}
											},
											error: function (XMLHttpRequest, textStatus, errorThrown) {
												$.messager.alert('消息', errorThrown);
											}
										})
									} else {
										return;
									}
								})
							} else {
								$.ajax({
									type: "post",
									dataType: "json",
									url: 'purchase/bill/group/check',
									data: JSON.stringify(model),
									contentType: "application/json",
									success: function (data) {
										$.messager.alert('消息', data.msg);
										if (data.code != 60200) {
										} else {
											$('#groId').val(data.data.groId)
											let dg = $('#dg');
											dg.datagrid('enableFilter');
											dg.datagrid('load');
											$('#addWindow').window('close');
										}
									},
									error: function (XMLHttpRequest, textStatus, errorThrown) {
										$.messager.alert('消息', errorThrown);
									}
								})

							}

						}

						function editrow(index) {
							if (index >= 0) {
								$('#dg').datagrid('selectRow', index);
							}
							//编辑
							var row = $('#dg').datagrid('getSelected');
							if (row) {
								console.log('row:', row)
								$('#fm').form('load', row);
								$('#oaCheckCob').combobox('setValue', row.oaCheckId);
								bindBillsGrid(row)
								bindGoodsList(row)

								$('#addWindow').window('open');
								$('#tabs').tabs('select', 0);
								if (row.status == '1') {
									$('#tabs').tabs('hideTool')
								} else {
									initTabTool();
								}
							} else {
								$.messager.alert('消息', '请选中一条数据');
							}
						}
					</script>
					<script>
						// 是否存在交货单
						function existGroId(rows, groId) {
							var flag = false;
							for (var i in rows) {
								if (rows[i].godId == groId) {
									return true;
								}
							}
							return flag;
						}


						/**
						* 将选中的计划物资添加到物资列表
						*/
						function addGood() {
							let mmDataGrid = $('#choiseGoodsList');
							const checkedmmRows = mmDataGrid.datagrid('getChecked');
							if (!checkedmmRows || checkedmmRows.length < 1) {
								$.messager.alert('提示', '请至少选择一条数据');
								return
							}
							if (checkedmmRows.length > 0 && checkedmmRows != null) {
								// 与已添加进物资明细的数据做对比，planId相同的不再重复添加
								const planMmrows = $('#goodsList').datagrid('getRows')
								for (let i in checkedmmRows) {
									// planMM 转换programMM
									let programMM = checkedmmRows[i]
									if (planMmrows.length > 0 && planMmrows != null) {
										//供应商是否一致
										if (programMM.infCode != planMmrows[0].infCode) {
											$.messager.alert('提示', '供应商不一致！');
											return
										}
										if (programMM.godTax != planMmrows[0].godTax) {
											$.messager.alert('提示', '税额不一致！');
											return
										}
										const result = existGroId(planMmrows, programMM.godId)
										if (!result) {
											$('#goodsList').datagrid('insertRow', {
												row: programMM
											})
										}
									} else {
										$('#goodsList').datagrid('insertRow', {
											row: programMM
										})
									}

								}
							}
							$('#choiseGoodWindow').window('close');
						}


						function selectGoodsList() {
							var startTime = $('#startGoodTime').datebox('getValue')
							var endTime = $('#endGoodTime').datebox('getValue')
							var dg = $('#choiseGoodsList');
							dg.datagrid('enableFilter');
							dg.datagrid('load', {
								startTime: startTime ? startTime : '',
								endTime: endTime ? endTime : '',
								status: 0
							});
							$('#choiseGoodsList').datagrid('clearChecked');
						}

						function bindChoiseGoodsList() {
							var startTime = $('#startGoodTime').datebox('getValue')
							var endTime = $('#endGoodTime').datebox('getValue')
							$('#choiseGoodsList').datagrid(
								{
									url: 'purchase/receive/good/selectList',
									queryParams: {
										startTime: startTime,
										endTime: endTime,
										status: 0
									},
									method: 'post',
									// title: '发票列表',
									iconCls: 'icon-application',
									width: 830,
									height: 310,
									nowrap: true,
									rownumbers: true,
									animate: false,
									collapsible: false,
									filterDelay: 0,
									clientPaging: false,
									remoteFilter: true,
									pagination: true,
									remoteSort: true,
									checkOnSelect: true,
									frozenColumns: [[{
										field: 'ck',
										checkbox: true,
										width: 50,
									}, {
										field: 'godId',
										title: '交货单id',
										sortable: true,
										hidden: true,
										formatter: function (val, rec) {
											return val ? unescape(val) : '';
										}
									}, {
										field: 'mmId',
										title: '物料id',
										sortable: true,
										hidden: true,
										formatter: function (val, rec) {
											return val ? unescape(val) : '';
										}
									}, {
										field: 'infCode',
										title: '供应商编码',
										sortable: true,
										formatter: function (val, rec) {
											return val ? unescape(val) : '';
										}
									}, {
										field: 'infName',
										title: '供应商名称',
										width: 200,
										sortable: true,
										formatter: function (val, rec) {
											return val ? unescape(val) : '';
										}
									}, {
										field: 'ordCode',
										title: '订单编号',
										sortable: true,
										width: 100,
										formatter: function (val, rec) {
											return val ? unescape(val) : '';
										}
									},]],
									columns: [[{
										field: 'godCode',
										title: '交货单号',
										sortable: true,
										width: 100,
										formatter: function (val, rec) {
											return val ? unescape(val) : '';
										}
									}, {
										field: 'mmCode',
										title: '物料号码',
										sortable: true,
										width: 100,
										formatter: function (val, rec) {
											return val ? unescape(val) : '';
										}
									}, {
										field: 'mmDetail',
										title: '物料描述',
										sortable: true,
										formatter: function (val, rec) {
											return val ? unescape(val) : '';
										}
									}, {
										field: 'planNum',
										title: '需求总数量',
										sortable: true,
										formatter: function (val, rec) {
											return val ? unescape(val) : '';
										}
									}, {
										field: 'godCompanyName',
										title: '公司',
										sortable: true,
										formatter: function (val, rec) {
											return val ? unescape(val) : '';
										}
									}, {
										field: 'mmUnit',
										title: '计量单位',
										sortable: true,
										formatter: function (val, rec) {
											return val ? unescape(val) : '';
										}
									}, {
										field: 'mmUnitDetail',
										title: '计量单位描述',
										sortable: true,
										formatter: function (val, rec) {
											return val ? unescape(val) : '';
										}
									}, {
										field: 'godIsWeight',
										title: '是否过磅',
										sortable: true,
										formatter: function (val, rec) {
											return val ? unescape(val) : '';
										}
									}, {
										field: 'godPlanDate',
										title: '计划交货日期',
										sortable: true,
										formatter: function (val, rec) {
											return val ? unescape(val) : '';
										}
									}, {
										field: 'godRealDate',
										title: '实际交货日期',
										sortable: true,
										formatter: function (val, rec) {
											return val ? unescape(val) : '';
										}
									}, {
										field: 'godBillNum',
										title: '开票数量',
										sortable: true,
										formatter: function (val, rec) {
											return val ? unescape(val) : '';
										}
									}, {
										field: 'godMoney',
										title: '开票金额',
										sortable: true,
										formatter: function (val, rec) {
											return val ? unescape(val) : '';
										}
									}, {
										field: 'godRowNum',
										title: '行项目号',
										sortable: true,
										formatter: function (val, rec) {
											return val ? unescape(val) : '';
										}
									}, {
										field: 'godChildRow',
										title: '次行项目号',
										sortable: true,
										formatter: function (val, rec) {
											return val ? unescape(val) : '';
										}
									}, {
										field: 'godCar',
										title: '车牌号码',
										sortable: true,
										formatter: function (val, rec) {
											return val ? unescape(val) : '';
										}
									}, {
										field: 'godOldNum',
										title: '原发数量',
										sortable: true,
										formatter: function (val, rec) {
											return val ? unescape(val) : '';
										}
									}, {
										field: 'godNewNum',
										title: '实收数量',
										sortable: true,
										formatter: function (val, rec) {
											return val ? unescape(val) : '';
										}
									}, {
										field: 'godTax',
										title: '税率',
										sortable: true,
										formatter: function (val, rec) {
											return val ? unescape(val) : '';
										}
									},
									{
										field: 'createTime',
										title: '创建时间',
										sortable: true,
										formatter: function (val, rec) {
											return unescape(val ? val : '')
										}
									}]],
									toolbar: [
										// 	{
										// 	text: '加入',
										// 	iconCls: 'icon-add',
										// 	handler: function () {
										// 		addGood();
										// 	}
										// },
									],
									onLoadSuccess: function () {
									},
									onDblClickRow: function () {

									}
								});
							$('#choiseGoodsList').datagrid('enableFilter');
						}

					</script>
					<script>

						// 移除所选
						function removeGood() {
							let Rows = $('#goodsList').datagrid('getSelected');
							if (!Rows) {
								$.messager.alert('提示', '请选择一条数据');
								return
							}
							// 获取索引
							let index = $('#goodsList').datagrid('getRowIndex', Rows);
							$('#goodsList').datagrid('deleteRow', index);
							$('#goodsList').datagrid('acceptChanges');
						}

						//物资明细
						function bindGoodsList(row) {
							var status = $('#status').combobox('getValue');
							$('#goodsList').datagrid(
								{
									url: 'purchase/bill/good/selectList',
									queryParams: {
										groId: row ? row.groId : ''
									},
									method: 'post',
									// title: '发票列表',
									iconCls: 'icon-application',
									width: 850,
									height: 300,
									nowrap: true,
									filterDelay: 0,
									rownumbers: true,
									animate: false,
									collapsible: false,
									clientPaging: false,
									remoteFilter: true,
									singleSelect: true,
									pagination: false,
									remoteSort: true,
									frozenColumns: [[{
										field: 'godId',
										title: '交货单id',
										sortable: true,
										hidden: true,
										formatter: function (val, rec) {
											return val ? unescape(val) : '';
										}
									}, {
										field: 'mmId',
										title: '物料id',
										sortable: true,
										hidden: true,
										formatter: function (val, rec) {
											return val ? unescape(val) : '';
										}
									}, {
										field: 'infCode',
										title: '供应商编码',
										sortable: true,
										formatter: function (val, rec) {
											return val ? unescape(val) : '';
										}
									}, {
										field: 'infName',
										title: '供应商名称',
										width: 200,
										sortable: true,
										formatter: function (val, rec) {
											return val ? unescape(val) : '';
										}
									}, {
										field: 'ordCode',
										title: '订单编号',
										sortable: true,
										width: 100,
										formatter: function (val, rec) {
											return val ? unescape(val) : '';
										}
									},]],
									columns: [[{
										field: 'godCode',
										title: '交货单号',
										sortable: true,
										width: 100,
										formatter: function (val, rec) {
											return val ? unescape(val) : '';
										}
									}, {
										field: 'mmCode',
										title: '物料号码',
										sortable: true,
										width: 100,
										formatter: function (val, rec) {
											return val ? unescape(val) : '';
										}
									}, {
										field: 'mmDetail',
										title: '物料描述',
										sortable: true,
										width: 150,
										formatter: function (val, rec) {
											if (val) {
												return '<span title="' + val + '">' + val + '</span>';
											} else {
												return val;
											}
										}
									}, {
										field: 'planNum',
										title: '需求总数量',
										sortable: true,
										formatter: function (val, rec) {
											return val ? unescape(val) : '';
										}
									}, {
										field: 'godCompanyName',
										title: '公司',
										width: 100,
										sortable: true,
										formatter: function (val, rec) {
											return val ? unescape(val) : '';
										}
									}, {
										field: 'mmUnit',
										title: '计量单位',
										sortable: true,
										formatter: function (val, rec) {
											return val ? unescape(val) : '';
										}
									}, {
										field: 'mmUnitDetail',
										title: '计量单位描述',
										sortable: true,
										formatter: function (val, rec) {
											return val ? unescape(val) : '';
										}
									}, {
										field: 'godIsWeight',
										title: '是否过磅',
										sortable: true,
										formatter: function (val, rec) {
											return val ? unescape(val) : '';
										}
									}, {
										field: 'godPlanDate',
										title: '计划交货日期',
										sortable: true,
										formatter: function (val, rec) {
											return val ? unescape(val) : '';
										}
									}, {
										field: 'godRealDate',
										title: '实际交货日期',
										sortable: true,
										formatter: function (val, rec) {
											return val ? unescape(val) : '';
										}
									}, {
										field: 'godBillNum',
										title: '开票数量',
										sortable: true,
										width: 100,
										formatter: function (val, rec) {
											return val ? unescape(val) : '';
										}
									}, {
										field: 'godMoney',
										title: '开票金额',
										sortable: true,
										width: 100,
										formatter: function (val, rec) {
											return val ? unescape(val) : '';
										}
									}, {
										field: 'godCar',
										title: '车牌号码',
										sortable: true,
										formatter: function (val, rec) {
											return val ? unescape(val) : '';
										}
									}, {
										field: 'godOldNum',
										title: '原发数量',
										sortable: true,
										formatter: function (val, rec) {
											return val ? unescape(val) : '';
										}
									}, {
										field: 'godNewNum',
										title: '实收数量',
										sortable: true,
										formatter: function (val, rec) {
											return val ? unescape(val) : '';
										}
									}, {
										field: 'godTax',
										title: '税率',
										sortable: true,
										formatter: function (val, rec) {
											return val ? unescape(val) : '';
										}
									},
									{
										field: 'createTime',
										title: '创建时间',
										sortable: true,
										formatter: function (val, rec) {
											return unescape(val ? val : '')
										}
									}]],
									toolbar: [{
										text: '增加',
										iconCls: 'icon-add',
										// disabled: status == '0' ? false : true,
										handler: function () {
											selectGoodsList();
											$('#choiseGoodsList').datagrid('clearChecked');
											$('#choiseGoodWindow').window('open');
										}
									},
										'-',
									{
										text: '删除',
										iconCls: 'icon-cancel',
										// disabled: status == '0' ? false : true,
										handler: function () {
											var row = $('#dg').datagrid(
												'getSelected');
											if (row) {
												if (+row.status == '1') {
													$.messager.alert('消息', '已提交，无法删除!');
													return
												}

												$.messager.confirm('提示', '确定要删除吗?', function (r) {
													if (r) {
														removeGood();

													}
												});
											} else {
												$.messager.alert('消息', '请选择数据!');
											}

										}
									}, '-', {
										text: '导出',
										iconCls: 'icon-export',
										handler: function () {
											exportMmList();
										}
									}],
									onLoadSuccess: function () {
									},
									onDblClickRow: function () {

									}
								});
						}

						// 导出采购计划列表
						function exportMmList() {
							let gramMmRows = $('#dg').datagrid('getSelected');
							var form = [];
							form.push('groId=' + gramMmRows.groId);
							let url = "api/purchase/bill/good/export";
							let xhr = new XMLHttpRequest()
							xhr.open('POST', url, true)
							xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
							xhr.setRequestHeader('token', localStorage.getItem('token'));
							xhr.setRequestHeader('userType', localStorage.getItem('userType'));
							xhr.responseType = 'blob'
							xhr.onload = function () {
								if (this.status == 200) {
									let blob = this.response
									let reader = new FileReader()
									reader.readAsDataURL(blob)
									reader.onload = function (e) {
										let a = document.createElement('a')
										a.download = '物资明细' + new Date().toLocaleDateString() + '-' + new Date().toLocaleTimeString() + '.xlsx'
										a.href = e.target.result
										$('body').append(a)
										a.click()
										$(a).remove()
									}
								}
							}
							xhr.send(form.join('&'))
						}
					</script>
					<script>
						//excle复制粘贴功能

						$(document).ready(function () {
							$(document.body).bind({
								paste: function (e) {
									if (window.clipboardData) {
										return;
									}
									if (editIndex != undefined) {
										return;
									}
									var clipboardData = e.originalEvent.clipboardData;
									processData(clipboardData);
								}
							});

							// document.onkeyup = function (e) {
							// 	if (window.clipboardData) {
							// 		e = window.event || e;
							// 		var keyCode = e.keyCode || e.which || e.charCode;
							// 		var ctrlKey = e.ctrlKey || e.metaKey;
							// 		if (ctrlKey && keyCode == 86) {
							// 			var clipboardData = window.clipboardData;
							// 			processData(clipboardData);
							// 		}
							// 	}
							// 	return false;
							// }
						});


						//粘贴函数
						var processData = function (clipboardData) {
							var data = clipboardData.getData('Text').split('\n');
							console.log('data:', data);
							var dataHtml = '';
							for (var i = 0; i < data.length; i++) {
								if (!data[i]) {
									continue;
								}
								console.log(data[i]);
								var bugdetData = data[i].split('\t');
								console.log(bugdetData);
								var row = {};
								row.bilCode = bugdetData[0];
								row.bilPrice = bugdetData[1];
								row.bilNum = bugdetData[2];
								row.bilTaxPrice = bugdetData[3];
								row.bilDate = bugdetData[4];
								$('#billsList').datagrid('insertRow', {
									row: row
								})

								// alert(bugdetData[0]);
							}
							// $('#billsList').datagrid('acceptChanges');
						};

						var editIndex = undefined;
						function endEditing() {
							if (editIndex == undefined) { return true }
							if ($('#billsList').datagrid('validateRow', editIndex)) {
								$('#billsList').datagrid('endEdit', editIndex);
								editIndex = undefined;
								return true;
							} else {
								// alert('请先完成本行数据录入！')
								return false;
							}
						}
						function onClickCell(index, field) {
							if (field == 'bilTotalPrice') {
								if (endEditing()) {
									$('#dg').datagrid('acceptChanges');
									console.log('bilTotalPrice', $('#billsList').datagrid('getRows'));
									$('#billsList').datagrid('getRows')[index].bilTotalPrice =
										Number($('#billsList').datagrid('getRows')[index].bilPrice) +
										Number($('#billsList').datagrid('getRows')[index].bilTaxPrice);
									$('#billsList').datagrid('refreshRow', index);
								}
							}
							if (editIndex != index) {
								if (endEditing()) {
									$('#billsList').datagrid('selectRow', index)
										.datagrid('beginEdit', index);
									var ed = $('#billsList').datagrid('getEditor', { index: index, field: field });
									if (ed) {
										($(ed.target).data('textbox') ? $(ed.target).textbox('textbox') : $(ed.target)).focus();
									}
									editIndex = index;
								} else {
									setTimeout(function () {
										$('#billsList').datagrid('selectRow', editIndex);
									}, 0);
								}
							}
						}
						function onEndEdit(index, row) {
							// var edPrice = $(this).datagrid('getEditor', {
							// 	index: index,
							// 	field: 'bilPrice'
							// });
							// var edTax = $(this).datagrid('getEditor', {
							// 	index: index,
							// 	field: 'bilTaxPrice'
							// });
							// row.bilTotalPrice = $(edPrice.target).numberbox('getValue')
							// 	+ $(edTax.target).numberbox('getValue');
						}
						function append() {
							if (endEditing()) {
								$('#billsList').datagrid('appendRow', {});
								editIndex = $('#billsList').datagrid('getRows').length - 1;
								$('#billsList').datagrid('selectRow', editIndex)
									.datagrid('beginEdit', editIndex);
							}
						}
						function removeit() {
							if (editIndex == undefined) { return }
							$('#billsList').datagrid('cancelEdit', editIndex)
								.datagrid('deleteRow', editIndex);
							editIndex = undefined;
						}

						function bindBillsGrid(row) {
							var status = $('#status').combobox('getValue');
							$('#billsList').datagrid(
								{
									url: 'purchase/bill/selectList',
									queryParams: {
										groId: row ? row.groId : ''
									},
									method: 'post',
									// title: '发票列表',
									iconCls: 'icon-application',
									width: 800,
									height: 300,
									nowrap: true,
									rownumbers: true,
									animate: false,
									collapsible: false,
									clientPaging: false,
									remoteFilter: true,
									filterDelay: 0,
									singleSelect: true,
									pagination: false,
									remoteSort: true,
									onClickCell: onClickCell,
									onEndEdit: onEndEdit,
									frozenColumns: [[]],
									columns: [[{
										field: 'groId',
										title: '批次id',
										sortable: true,
										hidden: true,
										formatter: function (val, rec) {
											return val ? unescape(val) : '';
										}
									}, {
										field: 'bilId',
										title: '发票id',
										sortable: true,
										hidden: true,
										formatter: function (val, rec) {
											return val ? unescape(val) : '';
										}
									}, {
										field: 'bilCode',
										title: '发票号',
										width: 100,
										formatter: function (val, rec) {
											return val ? unescape(val) : '';
										}, editor: { type: 'textbox', options: { required: true } }
									}, {
										field: 'bilPrice',
										title: '发票金额',
										width: 100,
										formatter: function (val, rec) {
											return val ? unescape(val) : '';
										}, editor: { type: 'numberbox', options: { precision: 2, required: true } }
									}, {
										field: 'bilNum',
										title: '发票数量',
										width: 100,
										formatter: function (val, rec) {
											return val ? unescape(val) : '';
										}, editor: { type: 'numberbox', options: { precision: 4, required: true } }
									}, {
										field: 'bilTaxPrice',
										title: '发票税额',
										width: 100,
										formatter: function (val, rec) {
											return val ? unescape(val) : '';
										}, editor: { type: 'numberbox', options: { precision: 2, required: true } }
									}, {
										field: 'bilDate',
										title: '发票日期',
										width: 100,
										formatter: function (val, rec) {
											return val ? unescape(val) : '';
										}, editor: { type: 'datebox', options: { editable: false, precision: 2, required: true } }
									}, {
										field: 'bilTotalPrice',
										title: '价税合计',
										width: 100,
										formatter: function (val, rec) {
											return val ? unescape(val) : '';
										}
									},]],
									toolbar: [{
										text: '增加',
										iconCls: 'icon-add',
										// disabled: status == '0' ? false : true,
										handler: function () {
											append();
										}
									},
										'-',
									{
										text: '删除',
										// disabled: status == '0' ? false : true,
										iconCls: 'icon-cancel',
										handler: function () {
											var row = $('#dg').datagrid(
												'getSelected');
											if (row) {
												if (+row.status == '1') {
													$.messager.alert('消息', '已提交，无法删除!');
													return
												}
												$.messager.confirm('提示', '确定要删除吗?', function (r) {
													if (r) { removeit() }
												});
											} else {
												$.messager.alert('消息', '请选择数据!');
											}
										}
									}],
									onLoadSuccess: function () {
									},
									onDblClickRow: function () {

									}
								});
						}

					</script>
					<script>
						/**
									 *  按条件查询报价列表
									 */
						function selectList() {
							var startTime = $('#startTime').datebox('getValue')
							var endTime = $('#endTime').datebox('getValue')
							var status = $('#status').combobox('getValue');
							var dg = $('#dg');
							dg.datagrid('enableFilter');
							dg.datagrid('load', {
								startTime: startTime ? startTime : '',
								endTime: endTime ? endTime : '',
								status: status ? status : ''
							});
						}

						function bindgrid() {
							var startTime = $('#startTime').datebox('getValue')
							var endTime = $('#endTime').datebox('getValue')
							var status = $('#status').combobox('getValue');
							// 							alert(PUser.userid);
							$('#dg').datagrid(
								{
									title: '',
									queryParams: {
										startTime: startTime,
										endTime: endTime,
										status: status
									},
									url: "purchase/bill/group/selectList",
									iconCls: 'icon-application',
									width: getWidth(0.98),
									height: 400,
									nowrap: true,
									filterDelay: 0,
									rownumbers: true,
									animate: false,
									collapsible: false,
									clientPaging: false,
									remoteFilter: true,
									singleSelect: true,
									pagination: true,
									remoteSort: true,
									frozenColumns: [[{
										field: 'groId',
										title: '批次id',
										sortable: true,
										hidden: true,
										formatter: function (val, rec) {
											return val ? unescape(val) : '';
										}
									}, {
										field: 'groCode',
										title: '批次编号',
										sortable: true,
										formatter: function (val, rec, index) {
											return '<a href="javascript:void(0)" onclick="editrow(' + index + ')">' + (val ? val : '') + '</a>';
										}
									}, {
										field: 'groName',
										title: '发票名称',
										sortable: true,
										formatter: function (val, rec) {
											return val ? unescape(val) : '';
										}
									},]],
									columns: [[{
										field: 'groOldNum',
										title: '累计原发数量',
										sortable: true,
										formatter: function (val, rec) {
											return val ? unescape(val) : '';
										}
									}, {
										field: 'groReceiveNum',
										title: '累计实收数量',
										sortable: true,
										formatter: function (val, rec) {
											return val ? unescape(val) : '';
										}
									},
									// }, {
									// 	field: 'infCode',
									// 	title: '供应商编号',
									// 	sortable: true,
									// 	formatter: function (val, rec) {
									// 		return val ? unescape(val) : '';
									// 	}
									// }, 
									{
										field: 'infName',
										title: '供应商名称',
										width: 200,
										sortable: true,
										formatter: function (val, rec) {
											return val ? unescape(val) : '';
										}
									}, {
										field: 'groOpenNum',
										title: '累计待开票数量',
										sortable: true,
										formatter: function (val, rec) {
											return val ? unescape(val.toLocaleString()) : '';
										}
									},
									{
										field: 'groNum',
										title: '累计发票数量',
										sortable: true,
										formatter: function (val, rec) {
											return val ? unescape(val.toLocaleString()) : '';
										}
									}, {
										field: 'groOpenPrice',
										title: '累计待开票金额',
										sortable: true,
										formatter: function (val, rec) {
											return val ? unescape(val.toLocaleString()) : '';
										}
									}, {
										field: 'groPrice',
										title: '累计发票金额',
										sortable: true,
										formatter: function (val, rec) {
											return val ? unescape(val.toLocaleString()) : '';
										}
									}, {
										field: 'groTaxPrice',
										title: '累计税额',
										sortable: true,
										formatter: function (val, rec) {
											return val ? unescape(val.toLocaleString()) : '';
										}
									}, {
										field: 'groTotalPrice',
										title: '累计价税合计',
										sortable: true,
										formatter: function (val, rec) {
											return val ? unescape(val.toLocaleString()) : '';
										}
									}, {
										field: 'oaCheckName',
										title: '会计审核人',
										sortable: true,
										formatter: function (val, rec) {
											return val ? unescape(val.toLocaleString()) : '';
										}
									}, {
										field: 'createTime',
										title: '创建时间',
										sortable: true,
										formatter: function (val, rec) {
											return val ? unescape(val) : '';
										}
									}, {
										field: 'createName',
										title: '创建人',
										sortable: true,
										formatter: function (val, rec) {
											return val ? unescape(val) : '';
										}
									}, {
										field: 'commitTime',
										title: '提交时间',
										sortable: true,
										formatter: function (val, rec) {
											return val ? unescape(val) : '';
										}
									}, {
										field: 'sapId',
										title: 'sap时间戳',
										sortable: true,
										formatter: function (val, rec) {
											return val ? unescape(val) : '';
										}
									}, {
										field: 'oaId',
										title: 'oa时间戳',
										sortable: true,
										formatter: function (val, rec) {
											return val ? unescape(val) : '';
										}
									}, {
										field: 'status',
										title: '状态',
										sortable: true,
										formatter: function (val, rec) {
											let status = val ? val : '';
											return unescape(status == '0' ? '待提交' : '已提交');
										}
									}, {
										field: 'remark',
										title: '备注',
										sortable: true,
										formatter: function (val, rec) {
											return val ? unescape(val) : '';
										}
									}]],
									toolbar: [{
										text: '增加',
										iconCls: 'icon-add',
										handler: function () {
											bindBillsGrid({ groId: '-1' });
											bindGoodsList({ groId: '-1' });
											$('#fm').form('clear');
											$('#addWindow').window('open');
											initTabTool();
										}
									},
										'-',
									{
										text: '编辑',
										iconCls: 'icon-edit',
										handler: function () {
											editrow()
										}
									},
										'-',
									{
										text: '删除',
										iconCls: 'icon-cancel',
										handler: function () {
											var row = $('#dg').datagrid(
												'getSelected');
											if (row) {
												if (+row.status == '1') {
													$.messager.alert('消息', '已提交，无法删除!');
													return
												}
												$.messager.confirm('提示', '确定要删除吗?', function (r) {
													if (r) { del(row); }
												});
											} else {
												$.messager.alert('消息', '请选择数据!');
											}
										}
									},
									{
										text: '撤回',
										iconCls: 'icon-undo',
										handler: function () {
											//撤回
											let row = $('#dg').datagrid('getSelected');
											if (row) {
												if (row.status == 0) {
													$.messager.alert('消息', '请选择已提交的数据。');
													return
												}
												$.messager.confirm('提示', '请先确认已退回流程在oa待办事宜里，确定要撤回吗?',
													function (r) {
														if (r) {
															backOrder()
														}
													});
											} else {
												$.messager.alert('消息', '请选择要撤回的数据。');
												return
											}
										}
									}],
									onLoadSuccess: function () {
									},
									onDblClickRow: function () {
										editrow();
									}
								});
							$('#dg').datagrid('enableFilter');
						}

						/**
						 *  撤回
						 */
						function backOrder() {
							let row = $('#dg').datagrid('getSelected');
							var data = {
								groId: row.groId,
								oaId: $('#oaIdNum').numberbox('getValue')
							}
							$.ajax({
								type: 'get',
								url: 'purchase/bill/group/recall?status=0&groId=' + row.groId,
								// data: JSON.stringify(data),
								contentType: "application/json",
								dataType: 'json',
								success: function (data) {
									if (data.code == 60200) {
										$.messager.alert('消息', data.msg)
										let dg = $('#dg');
										dg.datagrid('enableFilter');
										dg.datagrid('load');
										$('#backWindow').window('close');

									} else {
										$.messager.alert('消息', data.msg)
									}
								},
								error: function (XMLHttpRequest, textStatus, errorThrown) {
									$.messager.alert('消息', errorThrown);
								}
							})
						}

						function initTabTool() {
							$('#tabs').tabs({
								tools: [{
									text: '保存',
									iconCls: 'icon-save',
									handler: function () {
										save('save');
									}
								}, {
									text: '提交',
									iconCls: 'icon-ok',
									handler: function () {
										$.messager.confirm("提示", "提交后会推送sap,由sap定时发起挂账流程，确认提交?（注意：oa退回后不要删除流程，需先在cmp撤回）", function (e) {
											if (e) {
												save('submit')
											}
										})
									}
								}]
							})
							$('#tabs').tabs('select', 0);
						}
						function queryParams(data = {}, isPrefix = true, arrayFormat = 'brackets') {
							let prefix = isPrefix ? '?' : ''
							let _result = []
							let urlParams = '';
							if (['indices', 'brackets', 'repeat', 'comma'].indexOf(arrayFormat) == -1) arrayFormat = 'brackets';
							for (let key in data) {
								let value = data[key]
								// 去掉为空的参数
								if (['', undefined, null].indexOf(value) >= 0) {
									continue;
								}
								// 如果值为数组，另行处理
								if (value.constructor === Array) {
									// e.g. {ids: [1, 2, 3]}
									switch (arrayFormat) {
										case 'indices':
											// 结果: ids[0]=1&ids[1]=2&ids[2]=3
											for (let i = 0; i < value.length; i++) {
												_result.push(key + '[' + i + ']=' + value[i])
											}
											break;
										case 'brackets':
											// 结果: ids[]=1&ids[]=2&ids[]=3
											value.forEach(_value => {
												_result.push(key + '[]=' + _value)
											})
											break;
										case 'repeat':
											// 结果: ids=1&ids=2&ids=3
											value.forEach(_value => {
												_result.push(key + '=' + _value)
											})
											break;
										case 'comma':
											// 结果: ids=1,2,3
											let commaStr = "";
											value.forEach(_value => {
												commaStr += (commaStr ? "," : "") + _value;
											})
											_result.push(key + '=' + commaStr)
											break;
										default:
											value.forEach(_value => {
												_result.push(key + '[]=' + _value)
											})
									}
								} else {
									_result.push(key + '=' + value)
									urlParams += key + '=' + value
								}
							}
							console.log('_result:', _result);
							return _result.length ? prefix + _result.join('&') : ''
						}

						// 导出采购计划列表
						function exportList() {
							let startTime = $('#startTime').datebox('getValue')
							let endTime = $('#endTime').datebox('getValue')
							let status = $('#status').combobox('getValue')

							var form = [];
							form.push('startTime=' + (startTime ? startTime : ''));
							form.push('endTime=' + (endTime ? endTime : ''));
							form.push('status=' + (status ? status : ''));
							console.log('form:', form)
							let url = 'api/purchase/bill/group/export'
							let xhr = new XMLHttpRequest()
							xhr.open('POST', url, true)
							xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;');
							xhr.setRequestHeader('token', localStorage.getItem('token'));
							xhr.setRequestHeader('userType', localStorage.getItem('userType'));
							xhr.responseType = 'blob'
							xhr.onload = function () {
								if (this.status == 200) {
									let blob = this.response
									let reader = new FileReader()
									reader.readAsDataURL(blob)
									reader.onload = function (e) {
										let a = document.createElement('a')
										a.download = '采购发票' + new Date().toLocaleDateString() + '-' + new Date().toLocaleTimeString() + '.xlsx'
										a.href = e.target.result
										$('body').append(a)
										a.click()
										$(a).remove()
									}
								}
							}
							xhr.send(form.join('&'))
						}
						function adminBackClick() {
							$.messager.confirm('提示', '确定要撤回吗?',
								function (r) {
									if (r) {
										let row = $('#dg').datagrid('getSelected')
										backAdmin(row);
									}
								});
						}

						function backAdmin(resultObj) {
							if (resultObj) {
								let row = $('#dg').datagrid('getSelected');
								$.ajax({
									type: 'get',
									url: 'purchase/bill/group/recallAdmin?status=0&groId=' + row.groId,
									// data: JSON.stringify(data),
									contentType: "application/json",
									dataType: 'json',
									success: function (data) {
										if (data.code == 60200) {
											$.messager.alert('消息', data.msg)
											let dg = $('#dg');
											dg.datagrid('enableFilter');
											dg.datagrid('load');
											$('#backWindow').window('close');

										} else {
											$.messager.alert('消息', data.msg)
										}
									},
									error: function (XMLHttpRequest, textStatus, errorThrown) {
										$.messager.alert('消息', errorThrown);
									}
								})
							} else {
								alert('请选择一条数据！');
							}
						}
					</script>
					<style scoped="scoped">
						.textbox {
							height: 20px;
							margin: 0;
							padding: 0 2px;
							box-sizing: content-box;
						}

						/*.table tr {
        height: 15px;
    }*/
						input:disabled {
							background-color: #dae1ed;
						}
					</style>
					<div class="query_criteria" id="query_criteria">
						<div style="margin: 5px 0px">
							<%-- 搜索框 --%>
								<label style="font-size: 12px;">创建时间：</label> <input class="easyui-datebox"
									name="startTime" id="startTime"
									data-options="required:true,showSeconds:false,formatter:myformatter,parser:myparser"
									value="" style="width: 150px"> <label style="font-size: 10px;">~</label> <input
									class="easyui-datebox" name="endTime" id="endTime"
									data-options="required:true,showSeconds:false,formatter:myformatter,parser:myparser"
									style="width: 150px" /> <label
									style="margin-left: 20px; font-size: 12px;">状态：</label> <input
									class="easyui-combobox" id="status" name="status" style="width: 80px;" data-options="valueField: 'value',editable:false,
						textField: 'label',panelHeight:'auto',data: [{
							label: '全部',
							value: ''
						},{
							label: '待提交',
							value: '0',
							selected:true
						},{
							label: '已提交',
							value: '1'
						}]">
								</select> <a id="search" style="margin-left: 30px" href="javascript:void(0)"
									class="easyui-linkbutton" data-options="iconCls:'icon-search'"
									onclick="selectList()">查询</a> <a id="export" style="margin-left: 10px"
									href="javascript:void(0)" class="easyui-linkbutton"
									data-options="iconCls:'icon-export'" onclick="exportList()">导出</a>
								<a id="btnBack" href="javascript:void(0)" class="easyui-linkbutton"
									data-options="iconCls:'icon-search'" onclick="adminBackClick()">撤回</a>
						</div>
						<table id="dg"></table>

						<div id="addWindow" class="easyui-window" closed="true" modal="true" title="发票批次"
							style="width: 900px; height: 400px; padding: 5px 5px">
							<div class="easyui-tabs" id="tabs" style="width: 875px; height: 350px">
								<div title="基本信息">
									<form id="fm" class="ssec-form">
										<table class="table" style="margin: 5px 0 0 5px;">
											<tr>
												<td>
													<div class="ssec-label">批次编号：</div>
												</td>
												<td>
													<div class="ssec-text normal">
														<input id="groCode" name="groCode" class="easyui-textbox"
															data-options="disabled:true" />
													</div>
												</td>
												<td>
													<div class="ssec-label">发票名称：</div>
												</td>
												<td>
													<div class="ssec-text normal">
														<input id="groId" name="groId" type="hidden" /> <input
															id="groName" name="groName" class="easyui-textbox"
															data-options="required:true" />
													</div>
												</td>
											</tr>

											<tr>
												<td>
													<div class="ssec-label">原发数量：</div>
												</td>
												<td>
													<div class="ssec-text normal">
														<input id="groOldNum" name="groOldNum" class="easyui-textbox"
															data-options="disabled:true" />
													</div>
												</td>
												<td>
													<div class="ssec-label">实收数量：</div>
												</td>
												<td>
													<div class="ssec-text normal">
														<input id="groReceiveNum" name="groReceiveNum"
															class="easyui-textbox" data-options="disabled:true" />
													</div>
												</td>
											</tr>
											<tr>
												<td>
													<div class="ssec-label">待开票金额：</div>
												</td>
												<td>
													<div class="ssec-text normal">
														<input id="groPrice" name="groOpenPrice" class="easyui-textbox"
															data-options="disabled:true" />
													</div>
												</td>
												<td>
													<div class="ssec-label">待开票数量：</div>
												</td>
												<td>
													<div class="ssec-text normal">
														<input id="groNum" name="groOpenNum" class="easyui-textbox"
															data-options="disabled:true" />
													</div>
												</td>
											</tr>
											<tr>
												<td>
													<div class="ssec-label">发票金额：</div>
												</td>
												<td>
													<div class="ssec-text normal">
														<input id="groPrice" name="groPrice" class="easyui-textbox"
															data-options="disabled:true" />
													</div>
												</td>
												<td>
													<div class="ssec-label">发票数量：</div>
												</td>
												<td>
													<div class="ssec-text normal">
														<input id="groNum" name="groNum" class="easyui-textbox"
															data-options="disabled:true" />
													</div>
												</td>
											</tr>
											<tr>
												<td>
													<div class="ssec-label">会计审核人：</div>
												</td>
												<td>
													<div class="ssec-text normal">
														<input class="easyui-combobox" id="oaCheckCob" name="oaCheckCob"
															style="width: 60%;" data-options="required:true,valueField: 'value',editable:false,
			textField: 'label',panelHeight:'auto', url: 'sysDict/queryItemByTypeName?dicName=OA审核会计',
			method: 'get',
			valueField: 'dicValue',
			textField: 'dicName'">
													</div>
												</td>
												<!-- 
												<td>
													<div class="ssec-label">供应商名称：</div>
												</td>
												<td>
													<div class="ssec-text normal">
														<input id="infName" name="infName" class="easyui-textbox"
															data-options="disabled:true" />
													</div>
												</td> -->
											</tr>


											<tr>
												<td>
													<div class="ssec-label">备注：</div>
												</td>
												<td colspan="3">
													<div class="ssec-text normal">
														<input id="remark" name="remark" class="easyui-textbox"
															data-options="multiline:true,width:230,height:50" />
													</div>
												</td>
											</tr>
										</table>
									</form>
								</div>
								<div title="物资信息">
									<div style="margin: 5px 0 0 5px;">
										<table id="goodsList"></table>
									</div>
								</div>
								<div title="发票信息">
									<div style="margin: 5px 0 0 5px;">
										<table id="billsList"></table>
									</div>
								</div>
							</div>
						</div>

						<div id="backWindow" class="easyui-window" closed="true" modal="true" title="撤回发票"
							style="width: 900px; height: 400px; padding: 5px 5px">
							<div>请在oa打开退回的挂账流程，然后在浏览器地址栏中找到示例中标黑的数字，复制到下面框内，点击撤回<span></span></div>
							<div>
								http://oa.xyspec.com/spa/workflow/static4form/index.html?_rdm=1670479871643#/main/workflow/req?requestid=<span
									style="font-size: 18px;"><b>2920795</b></span>&isovertime=&_key=osc59g
							</div>
							<div style="margin: 5px 0px">
								<input id="oaIdNum" name="oaIdNum" class="easyui-numberbox"
									data-options="precision: 0" />
								<a id="search" style="margin-left: 30px" href="javascript:void(0)"
									class="easyui-linkbutton" data-options="iconCls:'icon-search'"
									onclick="backOrder()">撤回</a>
							</div>

						</div>
					</div>

					<div id="choiseGoodWindow" class="easyui-window" closed="true" modal="true" title="选择交货单"
						style="width: 900px; height: 400px; padding: 5px 5px">
						<div style="margin: 5px 0px">
							<%-- 搜索框 --%>
								<label style="font-size: 12px;">创建时间：</label> <input class="easyui-datebox"
									name="startGoodTime" id="startGoodTime"
									data-options="required:true,showSeconds:false,formatter:myformatter,parser:myparser"
									value="" style="width: 150px"> <label style="font-size: 10px;">~</label> <input
									class="easyui-datebox" name="endGoodTime" id="endGoodTime"
									data-options="required:true,showSeconds:false,formatter:myformatter,parser:myparser"
									style="width: 150px" /><a id="search" style="margin-left: 30px"
									href="javascript:void(0)" class="easyui-linkbutton"
									data-options="iconCls:'icon-search'" onclick="selectGoodsList()">查询</a><a
									id="searchBtn" style="margin-left: 5px" href="javascript:void(0)"
									class="easyui-linkbutton" data-options="iconCls:'icon-add'"
									onclick="addGood()">加入</a>
						</div>
						<table id="choiseGoodsList"></table>
					</div>
					</div>
		</body>

		</html>